﻿using System;
using RAP.Framework.Libary.Utils;

namespace RAP.Framework.Libary.Lock
{
	/// <summary>
	/// 
	/// </summary>
	public class LockScope
	{
		/// <summary>
		/// 
		/// </summary>
		public string Key { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public Func<bool> CheckLock { get; set; }

		/// <summary>
		/// 
		/// </summary>
		public Action LockBody { get; set; }

        /// <summary>
        /// 执行checkBody，如果返回true,则不会执行lockBody
        /// </summary>
        /// <param name="checkBody"></param>
        /// <returns></returns>
		public LockScope Check( Func<bool> checkBody )
		{
			this.CheckLock = checkBody;
			return this.doLock( );
		}

        /// <summary>
        /// 执行lockBody
        /// </summary>
        /// <param name="lockBody"></param>
        /// <returns></returns>
		public LockScope Action( Action lockBody )
		{
			this.LockBody = lockBody;
			return this.doLock( );
		}

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
		protected virtual LockScope doLock( )
		{
			if ( this.Key.IsNotNullOrEmpty( ) && this.CheckLock.IsNotNullOrEmpty( ) && this.LockBody.IsNotNullOrEmpty( ) )
			{
				GlobalLocks.Lock( this );
			}
			return this;
		}
	}
}